'use client';

import { useEffect, useState } from 'react';
import { Table, message, Button, Spin, Tag } from 'antd';
import { useUser } from '../../context/userContext';
import api from '../../utils/api';
import styles from '@/components/Font.module.css';

export default function PostManagementPage() {
    const [pendingPosts, setPendingPosts] = useState([]);
    const [totalPendingPosts, setTotalPendingPosts] = useState(0);
    const { user } = useUser();
    const accessToken = user? user.access_token : "";
    const [loading, setLoading] = useState(false);

    // 分页相关状态
    const [pendingPostsPage, setPendingPostsPage] = useState(1);
    const [pendingPostsPageSize, setPendingPostsPageSize] = useState(5);

    // 审核通过帖子
    const handleApprovePost = async (postId, authorId) => {
        setLoading(true);
        try {
            // 发送审核通过请求
            const approveResponse = await api.put(
                `/posts/approve?id=${postId}`,
                {}, 
                { headers: { Authorization: `Bearer ${accessToken}` } }
            );

            if (approveResponse.status === 200) {
                message.success('帖子审核通过');
                fetchPosts(pendingPostsPage, pendingPostsPageSize);
            }
        } catch (error) {
            console.error('审核通过处理出错:', error);
            message.error('审核通过操作失败');
        } finally {
            setLoading(false);
        }
    };

    // 审核拒绝帖子
    const handleRejectPost = async (postId) => {
        setLoading(true);
        try {
            // 发送审核拒绝请求
            const rejectResponse = await api.put(
                `/posts/reject?id=${postId}`,
                {}, 
                { headers: { Authorization: `Bearer ${accessToken}` } }
            );
            
            if (rejectResponse.status === 200) {
                message.success('帖子审核拒绝');
                fetchPosts(pendingPostsPage, pendingPostsPageSize);
            }
        } catch (error) {
            console.error('审核拒绝处理出错:', error);
            message.error('审核拒绝操作失败');
        } finally {
            setLoading(false);
        }
    };

    // 获取待审核帖子
    const fetchPosts = async (page = 1, pageSize = 10) => {
        setLoading(true);
        try {
            const response = await api.get('/posts/pending', {
                params: { page, pageSize },
                headers: { Authorization: `Bearer ${accessToken}` }
            });
            const postData = response.data || { posts: [], total: 0 };
            setPendingPosts(postData.posts || []);
            setTotalPendingPosts(postData.total || 0);
        } catch (error) {
            console.error('获取待审核帖子数据失败:', error);
            message.error('获取待审核帖子失败');
        } finally {
            setLoading(false);
        }
    };

    useEffect(() => {
        fetchPosts(pendingPostsPage, pendingPostsPageSize);
    }, [pendingPostsPage, pendingPostsPageSize]);

    const postColumns = [
        { 
            title: 'ID', 
            dataIndex: 'id', 
            key: 'id',
            className: styles.text,
            width: 80,
        },
        { 
            title: '内容标题', 
            dataIndex: 'title', 
            key: 'title',
            className: styles.text,
            width: 250,
        },
        { 
            title: '作者', 
            dataIndex: 'authorId', 
            key: 'authorId',
            className: styles.text,
            width: 120,
        },
        { 
            title: '状态', 
            dataIndex: 'status', 
            key: 'status',
            className: styles.text,
            width: 100,
            render: () => (
                <Tag 
                    color="#D6A7A1" 
                    style={{ fontFamily: 'var(--font-secondary)', fontSize: 14 }}
                >
                    待审核
                </Tag>
            )
        },
        {
            title: '操作',
            key: 'action',
            className: styles.text,
            width: 280,
            render: (_, record) => (
                <div className="flex space-x-2">
                    <Button 
                        type="primary" 
                        className="bg-[#D6A7A1] hover:bg-[#E8D6D0] text-white rounded-md transition-all text-sm px-3 py-1.5"
                        onClick={() => handleApprovePost(record.id, record.authorId)}
                    >
                        通过审核
                    </Button>
                    <Button 
                        type="primary" 
                        danger 
                        className="bg-[#A3989D] hover:bg-[#C1B7B0] text-white rounded-md transition-all text-sm px-3 py-1.5"
                        onClick={() => handleRejectPost(record.id)}
                    >
                        拒绝审核
                    </Button>
                </div>
            )
        }
    ];

    const postPagination = {
        current: pendingPostsPage,
        pageSize: pendingPostsPageSize,
        total: totalPendingPosts,
        onChange: (page, pageSize) => {
            setPendingPostsPage(page);
            setPendingPostsPageSize(pageSize);
            fetchPosts(page, pageSize);
        }
    };

    return (
        <div className="bg-[#F4EDEB] rounded-2xl shadow-md p-6">
            <h2 className={`${styles.titlesmall} text-xl mb-6 text-[#7A6E6E]`}>帖子管理</h2>
            <Spin spinning={loading}>
                <Table
                    columns={postColumns}
                    dataSource={pendingPosts}
                    pagination={postPagination}
                    className="rounded-xl overflow-hidden bg-white"
                    bordered={false}
                    rowClassName={(record, index) => index % 2 === 0 ? 'bg-white' : 'bg-[#F4EDEB]/50'}
                    size="middle"
                    components={{
                        header: {
                            cell: ({ className, ...restProps }) => (
                                <th
                                    {...restProps}
                                    className={`${className} ${styles.titlesmall} text-base font-semibold text-[#7A6E6E] bg-[#F4EDEB]`}
                                />
                            ),
                        },
                    }}
                />
            </Spin>
        </div>
    );
}